﻿using IdentityServer4.Models;
using IdentityServer4.Services;
using Microsoft.EntityFrameworkCore;

namespace Devonline.Identity.Admin;

public class ProfileService : IProfileService
{
    private readonly IdentityDbContext _context;
    public ProfileService(IdentityDbContext context)
    {
        _context = context;
    }

    public async Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        try
        {
            //depending on the scope accessing the user data.
            var claims = context.Subject.Claims.ToList();

            //set issued claims to return
            context.IssuedClaims = claims.ToList();

            await Task.CompletedTask;
        }
        catch (Exception)
        {
            //log your error
        }
    }

    public async Task IsActiveAsync(IsActiveContext context)
    {
        var userName = context.Subject.Claims.FirstOrDefault(x => x.Type == CLAIM_TYPE_USER_NAME)?.Value;
        context.IsActive = await _context.Users.AnyAsync(x => x.State == DataState.Available && x.UserName == userName);
    }
}